<?php

CCore::Using('net.pop3');
CCore::Using('labs.webmail');
CCore::Using('labs.webmail.folder');
CCore::Using('labs.webmail.protocols.inc.interface');
CCore::Using('labs.webmail.protocols.inc.exception');


class CCoreLabsWebMailProtocolsIncPop3 implements ICoreLabsWebMailProtocolsInc
{
	const OBJECT_ERROR_CODE = 1400;
	
	/**
	 * @var array
	 */
	private $_aExceptionErrors = array(
		0 => 'Неизвестный exception',
		1 => 'Ошибка коннекта',
		2 => 'Ошибка аунтефикации',
	);

	/**
	 * @var CCoreLabsWebMailAccount
	 */
	private $_oWebMailAccount;

	/**
	 * @var CCoreNetPop3
	 */
	private $_oPop3;

	/**
	 * @return CCoreLabsWebMailProtocolsIncImap
	 */
	public function __construct(CCoreLabsWebMailAccount $oWebMailAccount)
	{
		$this->_oWebMailAccount = $oWebMailAccount;
		$oPop3Config = new CCoreNetPop3Config(
			$oWebMailAccount->IncHost(), $oWebMailAccount->IncPort(),
			$oWebMailAccount->IncLogin(), $oWebMailAccount->incPassword(), 5, 5);

		$this->_oPop3 = new CCoreNetPop3($oPop3Config);
	}

	/**
	 * @return bool
	 */
	public function TestIncConnection()
	{
		if ($this->_oPop3->ConnectAndLogin())
		{
			return $this->_oPop3->LogoutAndDisconnect();
		}
		return false;
	}

	/**
	 * @return CCoreLabsWebMailFolderCollection
	 */
	public function Folders()
	{
		$oWebMailFolder = new CCoreLabsWebMailFolder();
		$oWebMailFolder->InitAsPop3InboxFolder();

		$oWebMailFolderCollection = new CCoreLabsWebMailFolderCollection();
		$oWebMailFolderCollection->Add($oWebMailFolder);

		return $oWebMailFolderCollection;
	}

	/**
	 * @return bool
	 */
	private function _connectAndLogin()
	{
		if (!$this->_oPop3->IsConnected())
		{
			if (!$this->_oPop3->Connect())
			{
				$this->_throwException('CCoreWebMailProtocolsIncException', 1);
			}

			if (!$this->_oPop3->Login())
			{
				$this->_throwException('CCoreWebMailProtocolsIncException', 2);
			}
		}

		return true;
	}

	/**
	 * @param string $sExceptionName
	 * @param int $iCode
	 * @return int
	 */
	private function _throwException($sExceptionName, $iCode)
	{
		if (!isset($this->_aExceptionErrors[$iCode]))
		{
			$iCode = 0;
		}
		
		throw new $sExceptionName($this->_aExceptionErrors[$iCode], $this->_getErrorCode(self::OBJECT_ERROR_CODE + $iCode));
	}
}
